# -*- coding:utf-8 -*-

import os
import sys
import time
import socket
import getpass

from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *



try:
    from cgai_io import copyfile
    import maya.cmds as cmds
    import shiboken2 
    import maya.OpenMayaUI as omui
    import Deadline.DeadlineConnect as Connect

    url = os.environ['DEADLINE_URL']
    port = int(os.environ['DEADLINE_PORT'])
    print('url:',url)
    print('port:',port)
    connectionObject = Connect.DeadlineCon(url,port)

except Exception as ERR:
    print('ERR:',ERR)


def maya_main_window():
    main_window_ptr = omui.MQtUtil.mainWindow()     #获得maya主窗口的指针，主要是为了让插件界面设置它为父窗口
    return shiboken2.wrapInstance(long(main_window_ptr), QWidget)  #把maya主窗口封装从QtGui对象



class DeadlineWin(QWidget):

    def __init__(self,parent=None):
        super(DeadlineWin,self).__init__(parent)

        self.M_font = QFont('',13,75)
        self.H_font = QFont('',10,55)
        self.setWindowTitle(u'提交Deadline')
        self.setWindowFlags(Qt.Window)
        self.setFixedSize(QSize(400, 520))
        self.main_layout = QVBoxLayout()
        self.main_layout.setAlignment(Qt.AlignTop)
        self.main_layout.setSpacing(30)
        self.pool_layout =  QHBoxLayout()
        self.pool_label = QLabel(u'机器池:')
        self.pool_label.setFont(self.M_font)
        self.pool_comb = QComboBox()
        self.pool_layout.addWidget(self.pool_label)
        self.pool_layout.addWidget(self.pool_comb)

        self.chunk_layout = QHBoxLayout()
        self.chunk_label = QLabel(u'连续帧:')
        self.chunk_label.setFont(self.M_font)
        self.chunk_eidt = QLineEdit()
        self.chunk_eidt.setText('10')
        intLimit = QIntValidator(1,99999,self)
        self.chunk_eidt.setValidator(intLimit)
        self.chunk_layout.addWidget(self.chunk_label)
        self.chunk_layout.addWidget(self.chunk_eidt)

        self.priority_layout = QHBoxLayout()
        self.priority_label = QLabel(u'优先级:')
        self.priority_label.setFont(self.M_font)
        self.priority_edit = QLineEdit()
        self.priority_edit.setText('50')
        intLimit1 = QIntValidator(0,100,self)
        self.priority_edit.setValidator(intLimit1)
        self.priority_layout.addWidget(self.priority_label)
        self.priority_layout.addWidget(self.priority_edit)

        self.project_dir_layout = QHBoxLayout()
        self.project_dir_layout.setSpacing(15)
        self.project_dir_label = QLabel(u'工程目录:')
        self.project_dir_label.setFont(self.M_font)
        self.project_dir_edit = QLineEdit()
        self.project_dir_btn = QPushButton('选择')
        self.project_dir_btn.clicked.connect(self._choose_project_dir)
        self.project_dir_patch_btn = QPushButton('自动')
        self.project_dir_patch_btn.clicked.connect(self.init_project_rendedr_dir)
        self.project_dir_layout.addWidget(self.project_dir_label)
        self.project_dir_layout.addWidget(self.project_dir_edit)
        self.project_dir_layout.addWidget(self.project_dir_btn)
        self.project_dir_layout.addWidget(self.project_dir_patch_btn)

        self.render_dir_layout = QHBoxLayout()
        self.render_dir_layout.setSpacing(15)
        self.render_dir_label = QLabel(u'输出目录:')
        self.render_dir_label.setFont(self.M_font)
        self.render_dir_eidt = QLineEdit()
        self.render_dir_btn = QPushButton('选择')
        self.render_dir_btn.clicked.connect(self._choose_render_dir)
        self.render_dir_patch_btn = QPushButton('自动')
        self.render_dir_patch_btn.clicked.connect(self.init_project_rendedr_dir)
        self.render_dir_layout.addWidget(self.render_dir_label)
        self.render_dir_layout.addWidget(self.render_dir_eidt)
        self.render_dir_layout.addWidget(self.render_dir_btn)
        self.render_dir_layout.addWidget(self.render_dir_patch_btn)
    

        self.submit_btn = QPushButton(u'提交Deadline')
        self.submit_btn.clicked.connect(self._submit)

        self.help_label = QLabel(u'说明:\n\n机器池:该任务所使用的机器池,none表示所有机器\n\n连续帧:每台任务打开文件后连续渲染多少帧\n\n优先级:0-100范围，值越大则越优先使用机器\n\n工程目录:ma文件所在目录\n\n输出目录:渲染文件输出目录')
        self.help_label.setFont(self.H_font)
        self.main_layout.addLayout(self.pool_layout)
        self.main_layout.addLayout(self.chunk_layout)
        self.main_layout.addLayout(self.priority_layout)
        self.main_layout.addLayout(self.project_dir_layout)
        self.main_layout.addLayout(self.render_dir_layout)
        self.main_layout.addWidget(self.submit_btn)
        self.main_layout.addWidget(self.help_label)
    
        self.setLayout(self.main_layout)

        self.init_pools()
        self.init_project_rendedr_dir()


    def init_pools(self):
        try:
            pools = connectionObject.Pools.GetPoolNames()
            self.pool_comb.addItems(pools)
        except Exception as PoolERR:
            print('PoolERR:',PoolERR)


    def init_project_rendedr_dir(self):
        try:
            # project_path = cmds.workspace(q=True,directory=1)
            ma_file = cmds.file(q=True,sn=True)
            if not ma_file:
                QMessageBox.information(None,'提示','请先保存文件')
                return False
            project_path = os.path.dirname(ma_file)
            self.project_dir_edit.setText(project_path)
            output_path = os.path.join(os.path.dirname(project_path),'images')
            self.render_dir_eidt.setText(output_path)
        except Exception as Project_Render_dir_ERR:
            print('Project_Render_dir_ERR:',Project_Render_dir_ERR)

    def _choose_project_dir(self):
        dir_path = QFileDialog.getExistingDirectory(self,u'选择文件夹')
        if dir_path:
            self.project_dir_edit.setText(dir_path)

    def _choose_render_dir(self):
        dir_path = QFileDialog.getExistingDirectory(self,u'选择文件夹')
        if dir_path:
            self.render_dir_eidt.setText(dir_path)



    def get_ip(self):
        s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        s.connect(("8.8.8.8",80))
        a = s.getsockname()
             
        return a[0]

    def replace2cgai_path(self,path):

        if 'CGAI' in path:
            split_path = path.split('CGAI')
            path = "//"+self.ip+"/cgai"+split_path[-1]
        else:
            print(u'注意:hip文件路径不包含CGAI,渲染输出路径可能会出现在deadline目录下')
        return path


    def save_deadline_ma(self):
        """
        save ma to deadline dir
        """
        ma_file = cmds.file(q=True,sn=True)
        if not ma_file:
            QMessageBox.information(None,'提示','请先保存文件')
            return False
        scenes_dir,fullname = os.path.split(ma_file)
        name,_type = os.path.splitext(fullname)
        deadline_dir = os.path.join(os.path.dirname(scenes_dir),'deadline')
        if not os.path.exists(deadline_dir):
            os.makedirs(deadline_dir)
        submit_time = time.strftime('%Y-%m-%d__%H-%M-%S')
        deadline_ma_path = os.path.join(deadline_dir,name+'_'+submit_time+_type)
        # tp = 'mayaAscii'
        # cmds.file(rename=deadline_ma_path)
        # cmds.file(save=True, typ=tp)
        cmds.file(save=1)
        copyfile(ma_file,deadline_ma_path)

        return deadline_ma_path

    def _submit(self):

        # print(self.size())
        deadline_ma_path = self.save_deadline_ma()
        if not deadline_ma_path:
            return
        try:
            # ma_file = cmds.file(q=True,sn=True)
            _,fullname = os.path.split(deadline_ma_path)
            name,_ = os.path.splitext(fullname)
            user_name = getpass.getuser()
            pool = self.pool_comb.currentText()
            chunk = self.chunk_eidt.text()
            chunk = int(chunk) if chunk else 1
            start = int(cmds.getAttr('defaultRenderGlobals.startFrame'))
            end = int(cmds.getAttr('defaultRenderGlobals.endFrame'))
            # plugin = 'Maya'
            priority = self.priority_edit.text()
            priority = int(priority) if priority else 50
            version = cmds.about(version=True)

            props = {}
            props['Name'] = user_name + '_' + name
            props['UserName'] = user_name
            props['Frames'] = '{}-{}'.format(start, end)
            props['Plugin'] = 'MayaBatch'
            props['Pool'] = pool
            props['Priority'] = priority
            props['ChunkSize'] = chunk

            project_path = self.project_dir_edit.text()
            project_net_path = self.replace2cgai_path(project_path)
            net_ma_path = self.replace2cgai_path(deadline_ma_path)
            output_path = self.render_dir_eidt.text()
            net_output_path = self.replace2cgai_path(output_path)

            plug = {
                    "ProjectPath":project_net_path,
                    "OutputFilePath": net_output_path,
                    "SceneFile": net_ma_path,
                    "Version": version
                    
                    }

            job = connectionObject.Jobs.SubmitJob(props, plug)
            print('job:',job)
            if job.get('_id'):
                # job_id = job['_id']
                QMessageBox.information(None,u'成功',u'提交成功')
            else:
                QMessageBox.information(None,u'失败',job)
        except Exception as ERR:
            QMessageBox.information(None,u'失败',u'提交失败\n'+str(ERR))

    # def closeEvent(self, *args, **kwargs):  #关闭事件设置为隐藏
    #     self.setHidden(True)


def maya_ui():
    MAINWIN = DeadlineWin(parent=maya_main_window()) #dialog if dialog else 
    MAINWIN.show()

# def maya_ui():
#     # print('start')
#     # global MAINWIN  #给一个全局变量记录窗口
#     try:
#         MAINWIN.show()
#         MAINWIN.setHidden(False)
#     except :
#         # print('new')
#         MAINWIN = DeadlineWin(parent=maya_main_window()) #dialog if dialog else 

#         MAINWIN.setHidden(False)



# if __name__ == '__main__':
#     app = QApplication(sys.argv)
#     # HOST = '192.168.1.109'
#     # PORT = 8081
#     # r_w = RefreshMovie()
#     # hm = HoudiniMonitor(HOST,PORT)
#     # hm.err_Signal.connect(lambda : r_w.deleteLater())
#     m = DeadlineWin()
#     m.show()
#     # r_w.finish(hm)
#     # r_w.deleteLater()
#     sys.exit(app.exec_())


